package com.example.nyf.common;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class BaseException {

    @ExceptionHandler(Exception.class)
    public Object exception(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        boolean isAjax = isAjax(request);
        if (isAjax) {
            return AjaxResult.error(handleException(exception));
        } else {
            ModelAndView mv = new ModelAndView();
            mv.addObject("errorMessage", handleException(exception));
            mv.setViewName("error_view");
            return mv;
        }
    }

    /**
     * 判断网络请求是否为ajax
     * @param req
     * @return
     */
    private boolean isAjax(HttpServletRequest req) {
        String contentTypeHeader = req.getHeader("Content-Type");
        String acceptHeader = req.getHeader("Accept");
        String xRequestedWith = req.getHeader("X-Requested-With");
        return (contentTypeHeader != null && contentTypeHeader.contains("application/json"))
                || (acceptHeader != null && acceptHeader.contains("application/json"))
                || "XMLHttpRequest".equalsIgnoreCase(xRequestedWith);
    }

    public String handleException(Throwable e) {
        if (e instanceof UnauthorizedException) {
            return " 权限不足 "+e.getMessage();
        } else if (e instanceof Error) {
            return e.getMessage();
        } else {
            return e.getMessage();
        }
    }

}
